import { ref } from 'vue'
import { defineStore } from 'pinia'
import userInit from '@/utils/userInit'

import type { UserFollow, UserBrowseData } from '@/TypingMore/UserTyping'

export const useCounterStore = defineStore('counter', () => {
  const userInitial = ref(userInit)

  const browseData = ref<any[]>([])

  const followUsers = ref<any[]>([])

  // 浏览记录
  const browseRecords = (obj: UserBrowseData) => {
    if (localStorage.getItem('browseData')) {
      let data = localStorage.getItem('browseData') as string
      browseData.value = JSON.parse(data)
      browseData.value = browseData.value.filter(item => {
        console.log(item.aid, obj.aid)
        return item.aid !== obj.aid
      })
    }

    browseData.value = [obj, ...browseData.value]
    localStorage.setItem('browseData', JSON.stringify(browseData.value))
  }

  // 关注
  const follow = (obj: UserFollow) => {
    if (localStorage.getItem('followUsers')) {
      let data = localStorage.getItem('followUsers') as string
      followUsers.value = JSON.parse(data)
      let count: number = 0
      followUsers.value.forEach(item => {
        if (item.mid !== obj.mid) {
          count++
        }
      })
      console.log(count , followUsers.value.length)
      if(count === followUsers.value.length) {
        followUsers.value = [obj, ...followUsers.value]
      } else {
        followUsers.value = followUsers.value.filter(item => {
          return item.mid !== obj.mid
        })
      }
      // followUsers.value = arr
    } else {
      followUsers.value = [obj, ...followUsers.value]
    }

  
    localStorage.setItem('followUsers', JSON.stringify(followUsers.value))
  }
  return { userInitial, browseRecords, follow }
})
